<template>
  <a-card title="Deployment 列表">
    <!-- Toolbar -->
    <div class="toolbar">
      <a-select v-model:value="selectedNamespace" placeholder="选择命名空间" @change="handleNamespaceChange"
                style="width: 200px">
        <a-select-option
            v-for="item in namespaces"
            :key="item.value"
            :value="item.value"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
      <a-button @click="handleRefresh">
        <template #icon>
          <ReloadOutlined/>
        </template>
        刷新
      </a-button>
      <a-button type="primary" @click="handleCreateDeployment">创建 Deployment</a-button>
      <a-button
          type="default"
          :disabled="selectedDeployments.length === 0"
          @click="handleBatchDelete"
          class="delete-btn"
      >
        批量删除
      </a-button>
    </div>

    <!-- Deployment List Table -->
    <a-table
        :columns="columns"
        :data-source="deployments"
        :row-key="'name'"
        size="small"
        style="width: 100%;"
        :row-selection="{
          selectedRowKeys: selectedDeploymentKeys,
          onChange: onSelectChange,
          checkStrictly: false
        }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'ready'">
          <span>{{ record.ready }}/{{ record.replicas }}</span>
        </template>
        <!-- <template v-if="column.key === 'phase'">
          <a-tag :color="record.phase === 'Available' ? 'green' : 'orange'">
            {{ record.phase }}
          </a-tag>
        </template> -->
        <template v-if="column.key === 'labels'">
          <a-tag v-for="(value, key) in record.labels" :key="key" class="label-tag">
            {{ key }}: {{ value }}
          </a-tag>
        </template>
        <template v-if="column.key === 'annotations'">
          <a-popover title="Annotations" :width="400" trigger="hover">
            <template #content>
              <div v-for="(value, key) in record.annotations" :key="key">
                {{ key }}: {{ value }}
              </div>
            </template>
            <a-button type="link">查看</a-button>
          </a-popover>
        </template>
        <template v-if="column.key === 'containers'">
          <div v-for="container in record.containers" :key="container.name">
              <span style="color: #00a86b; font-weight: bold;">{{ container.name }}</span>:
              <span>{{ container.image }}</span>
          </div>
        </template>
        <template v-if="column.key === 'age'">
          <span>{{ record.age }}</span>
        </template>
        <template v-if="column.key === 'strategy'">
          <span
            class="strategy-badge"
            :class="record.strategy"
          >
            {{ strategyMap[record.strategy] }}
          </span>
        </template>
        <template v-if="column.key === 'selector'">
          <a-tag v-for="(value, key) in record.selector" :key="key" class="label-tag">
            {{ key }}: {{ value }}
          </a-tag>
        </template>
      </template>
      <!-- <template #expandedRowRender="{record}">
        <a-table
            :columns="innerColumns"
            :data-source="record.containers"
            size="small"
            :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="record.status === 'Ready' ? 'green' : 'orange'">
                {{ record.status }}
              </a-tag>
            </template>
          </template>

        </a-table>
      </template> -->
    </a-table>

    <!-- Create Deployment Modal -->
    <a-modal
        v-model:open="createDialogVisible"
        title="创建 Deployment"
        @ok="submitCreateDeployment"
        @cancel="cancelCreateDeployment"
        width="1000px"
    >
      <div class="monaco-editor-container">
        <MonacoEditor
            v-model="deploymentYaml"
            @change="handleEditorChange"
            language="yaml"
            theme="vs-light"
            :options="editorOptions"
            style="height: 100%; border: 1px solid #dcdcdc; border-radius: 4px;"
        />
      </div>
    </a-modal>

    <!-- Delete Confirmation Modal -->
    <a-modal
        v-model:open="deleteConfirmVisible"
        title="确认删除"
        @ok="confirmDelete"
        okText="删除"
        cancelText="取消"
        okType="danger"
    >
      <p>是否确认删除以下 Deployment：</p>
      <ul>
        <li v-for="deployment in selectedDeployments" :key="deployment.name">{{ deployment.name }}</li>
      </ul>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { GetClusterDeploymentsByNamespace, DeleteDeployment, CreateDeploymentByYaml } from "@/api/cluster";
import MonacoEditor from "monaco-editor-vue3";


const props = defineProps({
  clusterId: {
    type: String,
    required: true
  },
  namespaces: {
    type: Array as () => Array<{ label: string; value: string }>,
    required: true
  }
});

const strategyMap: Record<string, string> = {
  RollingUpdate: '滚动更新',
  Recreate: '重新创建'
}

// Namespace state
const selectedNamespace = ref(props.namespaces[0].value);

// Deployment list state
const deployments = ref<any[]>([]);

// 选中的Deployment
const selectedDeployments = ref<any[]>([]);
const selectedDeploymentKeys = computed(() => selectedDeployments.value.map(deployment => deployment.name));
const deleteConfirmVisible = ref(false);

// Monaco Editor variables
const deploymentYaml = ref<string>('');
const editorOptions = {
  fontSize: 14,
  minimap: { enabled: false },
  automaticLayout: true,
}

const defaultPodYaml = `apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: nginx:latest
`;

// Table columns definition for Ant Design Table
const columns = [
  { title: '名称', dataIndex: 'name', key: 'name', width: 220 },
  { title: '副本数', dataIndex: 'replicas', key: 'replicas', width: 100 },
  { title: '就绪', dataIndex: 'ready', key: 'ready', width: 100 },
  // { title: '状态', dataIndex: 'phase', key: 'phase', width: 100 },
  { title: '标签', dataIndex: 'labels', key: 'labels' },
  { title: '注解', dataIndex: 'annotations', key: 'annotations' },
  { title: '容器', dataIndex: 'containers', key: 'containers' },
  { title: '存在时间', dataIndex: 'durationTime', key: 'durationTime', width: 120 },
  { title: '更新策略', dataIndex: 'strategy', key: 'strategy', width: 150 },
  { title: '选择器', dataIndex: 'selector', key: 'selector', width: 200 },
];

// Columns for the expanded container table
const innerColumns = [
  { title: '容器名称', dataIndex: 'name', key: 'name' },
  { title: '镜像', dataIndex: 'image', key: 'image' },
  { title: '端口', dataIndex: 'ports', key: 'ports' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

// Create Deployment dialog state
const createDialogVisible = ref(false);
const podForm = ref({
  name: '',
  image: '',
});


// --- MOCK DATA AND API FUNCTIONS ---
// In a real application, these would be API calls.



const fetchDeployments = async (namespace: string) => {
  // Simulate API call
  const { data } = await GetClusterDeploymentsByNamespace(props.clusterId, namespace);
  deployments.value = data.map(each => {
    const { "kubectl.kubernetes.io/last-applied-configuration": _, ...annotations } = each.metadata.annotations || {};
    return {
      name: each.metadata.name,
      replicas: each.spec.replicas,
      ready: each.status.readyReplicas,
      // phase: each.status.conditions[0].type,
      labels: each.metadata.labels || {},
      annotations: annotations,
      // durationTime: each.status.conditions[0].lastUpdateTime || '-',
      durationTime: each.status.durationTime || '-',
      strategy: each.spec.strategy.type || 'RollingUpdate',
      selector: each.spec.selector.matchLabels || {},
      containers: each.spec.template.spec.containers.map((container, idx) => {
        return {
          name: container.name,
          image: container.image,
          ports: container.ports || [],
          env: container.env || [],
          status: 'Ready',
        }
      }),
    }
  })
};
// --- LIFECYCLE AND HANDLERS ---

onMounted(() => {
  // 由于父组件确保了 namespaces prop 的存在，这里可以直接获取
  fetchDeployments(selectedNamespace.value);
});

watch(selectedNamespace, (newNamespace) => {
  fetchDeployments(newNamespace);
});

const handleNamespaceChange = (namespace: string) => {
  // The watch handler will automatically trigger fetchDeployments
  console.log(`Namespace changed to: ${namespace}`);
  selectedNamespace.value = namespace;
};

const handleRefresh = () => {
  fetchDeployments(selectedNamespace.value);
};

const handleCreateDeployment = () => {
  // 先设置模态框为打开状态
  createDialogVisible.value = true;
};

const handleEditorChange = (newValue: string) => {
  deploymentYaml.value = newValue;
};

const submitCreateDeployment = async () => {
  // Basic validation
  if (!deploymentYaml.value || !deploymentYaml.value.trim()) {
    message.error("Deployment YAML 不能为空")
    return;
  }

  try {
    await CreateDeploymentByYaml(parseInt(props.clusterId), deploymentYaml.value);
    message.success("Deployment 创建成功");
    createDialogVisible.value = false; // 关闭对话框
    // 延迟刷新以等待 Deployment 状态更新
    setTimeout(() => {
      fetchDeployments(selectedNamespace.value);
    }, 1000);
  } catch (error) {
    const errorMessage = error.response?.data?.message || '创建 Deployment 失败';
    message.error(errorMessage);
    console.error('Error creating deployment:', error);
  }
};

const cancelCreateDeployment = () => {
  // 先清空YAML内容，再关闭对话框
  deploymentYaml.value = '';
  createDialogVisible.value = false;
};

// 处理选择变化
const onSelectChange = (selectedRowKeys: string[], selectedRows: any[]) => {
  selectedDeployments.value = selectedRows;
};

// 处理批量删除：唤起“确认删除”对话框
const handleBatchDelete = () => {
  if (selectedDeployments.value.length === 0) {
    return;
  }
  deleteConfirmVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    // 创建删除操作的Promise数组
    const deletePromises = selectedDeployments.value.map(deployment =>
        DeleteDeployment(parseInt(props.clusterId), selectedNamespace.value, deployment.name)
    );

    // 等待所有删除操作完成
    await Promise.all(deletePromises);

    message.success(`已成功删除 ${selectedDeployments.value.length} 个 Deployment`);
    // 清空选中状态
    selectedDeployments.value = [];
    // 刷新列表
    fetchDeployments(selectedNamespace.value);
  } catch (error) {
    message.error('删除 Deployment 时发生错误');
    console.error('Error deleting deployments:', error);
  } finally {
    deleteConfirmVisible.value = false;
  }
};
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  align-items: center;
  margin-bottom: 16px;
}

.delete-btn {
  background-color: #eae8e8;
  border-color: #C0C0C0;

}

.label-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.expanded-row {
  padding: 8px 16px;
  background-color: #fafafa;
}

.expanded-row h4 {
  margin-bottom: 10px;
}
.monaco-editor-container {
  height: 600px; /* 设置编辑器高度 */
  width: 100%;
}

.strategy-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-weight: bold;
  font-size: 12px;
  display: inline-block;
}
.strategy-badge.RollingUpdate {
  background-color: #1677ff;
  color: white;
}
.strategy-badge.Recreate {
  background-color: #faad14;
  color: white;
}

.image-badge {
  background-color: #f0f0f0;
  color: #333;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-family: monospace;
  border: 1px solid #d9d9d9;
}

</style>
